"""
数据库模型定义模块
包含基础设施、主机及审计相关数据模型
"""
from django.db import models
from django_cryptography.fields import encrypt

class City(models.Model):
    """
    城市信息模型
    Attributes:
        name (str): 城市名称（唯一）
        code (str): 城市缩写代码（唯一）
    """
    name = models.CharField(max_length=50, unique=True, verbose_name="城市名称")
    code = models.CharField(max_length=10, unique=True, verbose_name="城市代码")

    def __str__(self):
        return f"{self.name} ({self.code})"

class IDC(models.Model):
    """
    互联网数据中心模型
    Attributes:
        name (str): IDC名称
        city (ForeignKey): 关联城市
        address (str): 详细地址
    """
    name = models.CharField(max_length=50, verbose_name="IDC名称")
    city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name="所在城市")
    address = models.TextField(verbose_name="详细地址")

    class Meta:
        verbose_name = "互联网数据中心"
        unique_together = ('city', 'name')  # 同一城市下IDC名称唯一

    def __str__(self):
        return f"{self.city.code}-{self.name}"

class Host(models.Model):
    """
    主机信息模型
    Attributes:
        hostname (str): 主机名（唯一）
        ip (str): IPv4地址
        idc (ForeignKey): 所属IDC
        root_password (str): 加密存储的root密码
        last_pwd_update (datetime): 最后密码更新时间
    """
    hostname = models.CharField(max_length=100, unique=True, verbose_name="主机名")
    ip = models.GenericIPAddressField(protocol='IPv4', verbose_name="IP地址")
    idc = models.ForeignKey(IDC, on_delete=models.CASCADE, verbose_name="所属IDC")
    root_password = encrypt(models.CharField(max_length=256, verbose_name="Root密码"))
    last_pwd_update = models.DateTimeField(auto_now=True, verbose_name="密码最后更新时间")

    class Meta:
        indexes = [
            models.Index(fields=['hostname', 'ip']),  # 组合索引优化查询
        ]
        verbose_name = "主机信息"

    def __str__(self):
        return f"{self.hostname} ({self.ip})"

class PasswordHistory(models.Model):
    """
    密码历史记录模型
    Attributes:
        host (ForeignKey): 关联主机
        password (str): 历史密码（加密存储）
        created_at (datetime): 记录创建时间
    """
    host = models.ForeignKey(Host, on_delete=models.CASCADE, verbose_name="所属主机")
    password = encrypt(models.CharField(max_length=256, verbose_name="历史密码"))
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="记录时间")

    class Meta:
        ordering = ['-created_at']  # 默认按时间倒序排列
        verbose_name = "密码历史记录"

class DailyStat(models.Model):
    """
    每日统计报表模型
    Attributes:
        city (ForeignKey): 关联城市
        idc (ForeignKey): 关联IDC
        host_count (int): 主机数量统计
        stat_date (date): 统计日期
    """
    city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name="城市")
    idc = models.ForeignKey(IDC, on_delete=models.CASCADE, verbose_name="IDC")
    host_count = models.IntegerField(default=0, verbose_name="主机数量")
    stat_date = models.DateField(auto_now_add=True, verbose_name="统计日期")

    class Meta:
        unique_together = ('idc', 'stat_date')  # 防止重复统计
        verbose_name = "每日统计"
        indexes = [
            models.Index(fields=['stat_date']),
        ]

    def __str__(self):
        return f"{self.stat_date} - {self.idc} 主机数: {self.host_count}"